<?php

namespace App\Http\Controllers\Family;

use App\Library\AdvancedRateLimiter;
use App\Models\Family;
use App\Support\AliyunSms;
use App\Models\SmsCode;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Facades\JWTAuth;

/**
 * 用户登录
 * Class LoginController
 * @package App\Http\Controllers\Api
 */
class LoginController extends BaseController
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * 最多错误次数
     * @var int
     */
    protected $maxAttempts = 3;

    /**
     * 错误间隔时间(分钟)
     * @var int
     */
    protected $decayMinutes = [1, 3, 10, 60, 600];

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //$this->middleware('guest:web')->except('logout');
    }

    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        if (Auth::guard('family')->check()){

            return redirect()->route('family.home');
        }

        return familyView('login.index');
    }

    /**
     * Handle a login request to the application.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response|void
     * @throws \Illuminate\Validation\ValidationException
     */
    public function login(Request $request)
    {
        $this->validateLogin($request);

        /* 错误次数验证 */
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            $seconds = $this->limiter()->availableIn(
                $this->throttleKey($request)
            );

            return back()->with('error', __('auth.throttle', ['seconds' => $seconds]))->withInput();
        }

        $mobile = $request->input('phone');

        /**
         * @var $family Family
         */
        //$user = User::where('mobile', encryptStr($mobile))->first();
        $family = Family::where('phone', $mobile)->first();

        if (!$family) {
            /* 增加错误次数 */
            $this->incrementLoginAttempts($request);
            return back()->with('error', '用户不存在')->withInput();
        }

        // 验证短信验证码
        $smsCode = $request->input('sms_code');

        if (SmsCode::verify($mobile, $smsCode, SmsCode::TYPE_LOGIN)) {
            // 登录
            Auth::guard('family')->login($family);

            return $this->sendLoginResponse($request);
            //return back()->withErrors(['sms_code' => __('SMS Verification Code incorrect or expired')])->withInput();
        }
        Log::error("no");
        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

    /**
     * Get the failed login response instance.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @throws ValidationException
     */
    protected function sendFailedLoginResponse(Request $request)
    {
        throw ValidationException::withMessages([
            //$this->username() => [trans('auth.failed')],
            $this->username() => ["验证码错误"],
        ]);
    }

    /**
     * Log the user out of the application.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout(Request $request)
    {
        Auth::guard('family')->logout();

        return redirect()->route('family.login');
    }

    /**
     * Increment the login attempts for the user.
     *
     * @param \Illuminate\Http\Request $request
     * @return void
     */
    protected function incrementLoginAttempts(Request $request)
    {
        $this->limiter()->hit(
            $this->throttleKey($request), array_map(function ($decayMinute) {
                return (int)($decayMinute * 60);
            }, (array)$this->decayMinutes())
        );
    }

    /**
     * Validate the user login request.
     *
     * @param \Illuminate\Http\Request $request
     * @return void
     */
    protected function validateLogin(Request $request)
    {
        $this->validate($request, [
            $this->username() => 'required|string',
            'sms_code' => 'required|string',
        ], [], []);
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return \Tymon\JWTAuth\JWTGuard
     */
    protected function guard()
    {
        return Auth::guard('family');
    }

    /**
     * Where to redirect users after login.
     *
     * @return string
     */
    protected function redirectTo()
    {
        return route('family.home');
    }

    /**
     * 更改高级设置登录错误次数
     * @return \Illuminate\Foundation\Application|mixed
     */
    protected function limiter()
    {
        return app(AdvancedRateLimiter::class);
    }

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function username()
    {
        return 'phone';
    }

    /**
     * Send the response after the user was authenticated.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());

    }

    /**
     * 登录发送短信
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function sendSms(Request $request)
    {
        if ($request->ajax()) {
            $data = [
                'error' => 0,
                'message' => '短信已发送'
            ];

            $mobile = $request->input('phone');
            if (empty($mobile)) {
                $data = [
                    'error' => 1,
                    'message' => __('validation.required', ['attribute' => __('Mobile')])
                ];
                return response()->json($data);
            }

            //$user = User::where('mobile', encryptStr($mobile))->where('is_complete', 1)->first();
            $family = Family::where('phone',$mobile)->first();
            if (!$family) {
                $data = [
                    'error' => 1,
                    'message' => '手机号不存在或未注册完成'
                ];
                return response()->json($data);
            }

            $code = geneSmsCode(4);

            $aliyunSms = new AliyunSms();

            if (!$aliyunSms->send($mobile, $code)) {
                $data = [
                    'error' => 1,
                    'message' => __('Send failed, please try again later')
                ];
                return response()->json($data);
            }

            if (!SmsCode::send($mobile, $code, SmsCode::TYPE_LOGIN)) {
                $data = [
                    'error' => 1,
                    'message' => ''
                ];
                return response()->json($data);
            }

            return response()->json($data);
        }

        return redirect()->route('login');
    }
}
